/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package	dao;

import Hibernate.HibernateUtil;
import pojo.Author;
import pojo.Book;
import pojo.Publisher;
import pojo.Topic;
import pojo.Translator;


import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class BookDAO extends AbstractDAO {

	@Override
	protected Class getPOJOClass() {
		// TODO Auto-generated method stub
		return Book.class;
	}
	
    public Book getBookByID(int id){
        Book book = null;
        Session session = HibernateUtil.getSessionFactory().openSession();
        try{
            book = (Book)session.get(Book.class, id);
        }
        catch(HibernateException ex){
            
        }
        finally{
            session.close();
        }
        return book;
    }
    
    public int insert(String name, int authorID, int translatorID, int publisherID, int pageNum, float width, float height, float weight, double price, Date publishDay, String content){
    	Book book = new Book();
    	AuthorDAO authordao = new AuthorDAO();
    	TranslatorDAO translatordao = new TranslatorDAO();
    	PublisherDAO publisherdao = new PublisherDAO();
    	book.setName(name);
    	book.setAuthor(authordao.getAuthorByID(authorID));
    	book.setTranslator(translatordao.getTranslatorByID(translatorID));
    	book.setPublisher(publisherdao.getPublisherByID(publisherID));
    	book.setPageNum(pageNum);
    	book.setWidth(width);
    	book.setHeight(height);
    	book.setWeight(weight);
    	book.setPrice(price);
    	book.setPublishDay(publishDay);
    	book.setContent(content);
    	
    	Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		try {
			transaction = session.beginTransaction();
			session.save(book);
			transaction.commit();
		} catch (HibernateException ex) {
			// Log the exception
			transaction.rollback();
		}
		finally {
			session.close();
		}
		
		return book.getBookId();
    }
    public Book returnBook(String name, Author author, Translator translator, Publisher publisher, int pageNum, float width, float height, float weight, double price, Date publishDay, String content){
    	Book book = new Book();
    	//AuthorDAO authordao = new AuthorDAO();
    	//TranslatorDAO translatordao = new TranslatorDAO();
    	//PublisherDAO publisherdao = new PublisherDAO();
    	book.setName(name);
    	book.setAuthor(author);
    	book.setTranslator(translator);
    	book.setPublisher(publisher);
    	book.setPageNum(pageNum);
    	book.setWidth(width);
    	book.setHeight(height);
    	book.setWeight(weight);
    	book.setPrice(price);
    	book.setPublishDay(publishDay);
    	book.setContent(content);
    	
    	//Session session = HibernateUtil.getSessionFactory().openSession();
		//Transaction transaction = null;
		//try {
		//	transaction = session.beginTransaction();
		//	session.save(book);
		//	transaction.commit();
		//} catch (HibernateException ex) {
			// Log the exception
		//	transaction.rollback();
		//}
		//finally {
		//	session.close();
		return book;
		//}
    }
    
    
    public static synchronized int insert(Book book)
    {
    	List<Book> temp = getBookByUrl(book.getBookUrl());
    	if(temp.isEmpty()){
    		book.setIsNew("true");
    	}else{
    		double tprice = temp.get(0).getPrice();
    		double bprice = book.getPrice();
    		if(tprice != bprice){
    			temp.get(0).setPrice(book.getPrice());
    			if(temp.get(0).getIsNew().compareTo("false") == 0)
    				temp.get(0).setIsNew("true");
    		}else{
    		}
    		book = temp.get(0);
    	}
    	Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		try {
			transaction = session.beginTransaction();
			session.saveOrUpdate(book);
			//int n=book.getBookId();
			//book.setImageUrl(Integer.toString(n));
			//session.update(book);
			transaction.commit();
		} catch (HibernateException ex) {
			// Log the exception
			System.out.println(ex);
			transaction.rollback();
			return -1;
		}
		
		try{
			transaction = session.beginTransaction();
			int n = book.getBookId();
			book.setImageUrl(Integer.toString(n));
			session.update(book);
			transaction.commit();
		}catch(HibernateException ex){
			System.out.println(ex);
			transaction.rollback();
		}finally{
			session.close();
		}
		return book.getBookId();
    }
    private static List<Book> getBookByUrl(String url){
    	List<Book> ds = null;
    	Session session = HibernateUtil.getSessionFactory().openSession();
		String hql = "from Book as b where b.bookUrl like :url";
		Query query = session.createQuery(hql);
		query.setString("url", url);
		try{
			ds = query.list();
		}catch(HibernateException e){
			e.printStackTrace();
			//ds = new ArrayList<Book>();
		}
		
		
		session.close();
		return ds;
    }
    public int delete(Book book)
    {
    	Session session = HibernateUtil.getSessionFactory().openSession();
    	Book b=this.getBookByID(book.getBookId());
		Transaction transaction = null;
		try {
			transaction = session.beginTransaction();
			session.delete(b);
			session.flush();
			transaction.commit();
		} catch (HibernateException ex) {
			// Log the exception
			System.out.println(ex);
			transaction.rollback();
		}
		finally {
			session.close();	
		}
		
		
		return book.getBookId();
    }
    
    public List<Book> getBookBySize(int size)
    {
    	List<Book> ds = null;
		Session session = HibernateUtil.getSessionFactory().openSession();
		String hql = "select s from Book s";
		Query query = session.createQuery(hql);
		 ds = (List<Book>) query.list();
		session.close();
		return ds;
    }
    
	public void update(Book b) {
		// TODO Auto-generated method stub
    	Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		try {
			transaction = session.beginTransaction();
			session.update(b);
			session.flush();
			transaction.commit();
		} catch (HibernateException ex) {
			// Log the exception
			System.out.println(ex);
			transaction.rollback();
		}
		finally {
			session.close();	
		
	}
	}
    public List<Book> getNbookTopView(int n)
    {
    	List<Book> ds=null;
		Session session = HibernateUtil.getSessionFactory().openSession();
		String hql = "select s from Book s order by s.view desc";
		Query query = session.createQuery(hql);
		query.setMaxResults(n);
		ds = (List<Book>) query.list();
		session.close();
		return ds;
    
    }
    public List<Book> getBookByIsNew(){
    	List<Book> ds = null;
    	Session session = HibernateUtil.getSessionFactory().openSession();
		String hql = "from Book as b where b.isNew like :isNew";
    	//String hql = "from Author";
		Query query = session.createQuery(hql);
		 
		query.setString("isNew", "true");
		ds = query.list();
		session.close();
		updateBookTable();
		return ds;
    }
    private void updateBookTable(){
    	Session session = HibernateUtil.getSessionFactory().openSession();
    	Transaction transaction = null;
    	String hql = "update Book as b set b.isNew = :old " +
    				 "where b.isNew like :new";
    	Query query = session.createQuery(hql);
    	query.setString("old", "false");
    	query.setString("new", "true");
    	try{
    		transaction = session.beginTransaction();
    		int result = query.executeUpdate();
    		transaction.commit();
    	}catch(HibernateException e){
    		e.printStackTrace();
    		transaction.rollback();
    	}finally{
    		session.close();
    	}
    }
}
